"""
Create a simulation of this system where half the time the input travels through component A.
To simulate its reliability, generate a number between 0 and 1. If the number is 0.85 or below,
component A succeeded, and the system works. The other half of the time, the input would travel on the lower half of the diagram.
To simulate this, you will generate two numbers between 0 and 1.
If the number for component B is less than 0.95 and the number for component C is less than 0.90, then the system also succeeds.
Run many trials to see if you converge on the same reliability as predicted by probability theory.


Author: Zhangjinwei 21215158
"""
import random as rd


def components(reliability: float):
    return rd.random() < reliability


def the_flow(seq_no: int):
    if seq_no % 2 == 0:
        # P(A)= 0.85
        return components(0.85)
    else:
        # P(C|B) * P(B) = 0.855
        return components(0.90) if components(0.95) else False


if __name__ == '__main__':
    for i in range(4, 32):
        trail = 2 ** i
        assert trail % 2 == 0, '两边测试数相等，测试必须为偶数'
        success_cnt = 0
        for i in range(trail):
            success_cnt += the_flow(trail)
        print('Total trail times: %d, succeed %d times, success rate %0.6f' % (trail, success_cnt, success_cnt/trail))


